#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#-------------------------------python----------------------colorch.py--#
#                                                                       #
#                          Scelta del colore                            #
#                                                                       #
#--Daniele Zambelli--------------GPL-----------------------------2005---#

import Tkinter as tk
from pyplot import Plot

####
# Costanti relative a dimensioni e posizioni
###
DIMCOLOR=16
RANGE=("00", "20", "40", "60", "80", "a0", "c0", "e0", "ff")
ICOLORI=("R", "G", "B")
STRINGHECOLOR=("#%s0000", "#00%s00", "#0000%s")
##R=0
##G=1
##B=2

class Palette(tk.Frame):
  """Classe che realizza l'applicazione."""
  
  def __init__(self, master):
    """Inizializza i vari attributi, crea i widgets e collega gli eventi."""
    tk.Frame.__init__(self, master, relief=tk.RIDGE, bd=4)
    self.rgb=["00", "00", "00"]
    self.color="#000000"
    self.cursori = self.createWidgets()
    self.bindhandlers()
##    self.p.move(self.cr, 3*DIMCOLOR, 3*DIMCOLOR)

  def createWidgets(self):
    """Crea i widgets."""
    top=self.master
    self.p=tk.Canvas(top, width=DIMCOLOR*3, height=DIMCOLOR*12)
    self.p.grid(row=0, column=0)
    # tavolozza
    cursori=[]
    for j in xrange(3):
      sc=STRINGHECOLOR[j]
      x1=j*DIMCOLOR; x2=(j+1)*DIMCOLOR
      self.p.create_text((x1+x2)/2, DIMCOLOR/2, text=ICOLORI[j])
      for i, c in enumerate(RANGE):
        self.p.create_rectangle(x1, (i+1)*DIMCOLOR, x2, (i+2)*DIMCOLOR,
                                fill=sc % (c,))
      cursori.append(self.p.create_rectangle(x1+2, DIMCOLOR+2,
                                             x2-1, 2*DIMCOLOR-1,
                                             outline="white"))
    # risultato
    self.rcolor=self.p.create_rectangle(0, 10*DIMCOLOR,
                                         3*DIMCOLOR, 12*DIMCOLOR,
                                         fill=self.color)
    return cursori


  def bindhandlers(self):
    """Collega gli eventi ai metodi."""
    self.p.bind("<1>", self.mouseDown)

  def mouseDown(self, event):
    """Chiamato quando viene premuto il mouse sul cursore x.
    Gestiscono la scelta della componente del colore."""
    color=int(event.x/DIMCOLOR)
    gradazione=int(event.y/DIMCOLOR-1)
    if 0<=color<3 and 0<=gradazione<9:
      self.p.coords(self.cursori[color],
                    color*DIMCOLOR+2, (gradazione+1)*DIMCOLOR+2,
                    (color+1)*DIMCOLOR-1, (gradazione+2)*DIMCOLOR-1)
      self.rgb[color]=RANGE[gradazione]
      self.color="#%s%s%s" % tuple(self.rgb)
      self.p.itemconfig(self.rcolor, fill=self.color)
      self.event_generate("<Pause>")

  def getcolor(self):
    return self.color

def main():
  root=tk.Tk()
  a=Palette(root)
  root.mainloop()


if __name__ == "__main__" : main ()
